const {db} = require("../../config/dbconfig");


//分页查询所有文章
exports.getPosts = (req, res, next) => {
    const sql = "SELECT id,title,imgUrl,tags,likes,updated_at,liulan FROM posts ORDER BY updated_at DESC LIMIT ?,?";
    db.query(sql, [req.query.start, req.query.end], (err, result) => {
        if (err) throw err; else {
            console.log(result)
        }

        return res.cc(result, 0)
    });
}
exports.getAllPosts = (req, res, next) => {
    // console.log(req)
    //查询数据库中的条数
    const sql1 = "SELECT id FROM posts";
    db.query(sql1, (err, result1) => {
        if (err) throw err;
        let size = result1.length;
        const sql = "SELECT id,title,imgUrl,tags,likes,updated_at,liulan FROM posts ORDER BY updated_at DESC LIMIT ?,?";
        db.query(sql, [Number(req.query.start), Number(req.query.end)], (err, result) => {
            if (err) throw err;
            //将result[0].tags作为对象形式返回
            for (let i = 0; i < result.length; i++) {
                result[i].tags = result[i].tags.split(/[，,]/);
            }
            // console.log(result)
            const data = {
                data: result, length: size
            }
            return res.cc(data, 0)
        });
    });


}
exports.getPostsById = (req, res, next) => {
    const sql = "SELECT * FROM posts WHERE id = ?";
    db.query(sql, req.params.id, (err, result) => {
        if (err) throw err;
        return res.cc(result, 0)
    });
}
exports.getHotPosts = (req, res, next) => {
    const sql = "SELECT id,title FROM posts ORDER BY likes DESC limit 3";
    db.query(sql, (err, result) => {
        if (err) throw err;
        return res.cc(result, 0)
    });
}
exports.getLikePosts = (req, res, next) => {
    const sql = "SELECT id,title FROM posts WHERE likes > 0 ORDER BY liulan DESC";
    db.query(sql, (err, result) => {
        if (err) throw err;
        return res.cc(result, 0)
    });
}

exports.createPost = (req, res, next) => {
    let {title, content, imgUrl, tags} = req.body;
    console.log(tags)
    const likes = 0, liulan = 0
    // 插入数据的 SQL
    const sql = `INSERT INTO posts (title, content, imgUrl, tags, likes, liulan) VALUES (?, ?, ?, ?, ?, ?)`;
    const values = [title, content || null, imgUrl || null, tags || null, likes, liulan];
    db.query(sql, values, (err, result) => {
        if (err) {
            console.error('插入数据失败:', err);
            return res.status(500).json({error: 'Failed to insert post'});
        }
        res.status(201).cc({message: 'Post created successfully', postId: result.insertId}, 0);
    });

}
exports.updatePost = (req, res, next) => {
    const {id} = req.params; // 获取路径参数中的 post ID
    const {title, content, imgUrl, tags, likes, liulan} = req.body; // 获取请求体中的数据
    console.log(tags)
    // 验证 ID 是否存在
    if (!id) {
        return res.status(400).cc({error: 'Post ID is required'});
    }
    // 创建动态更新字段的 SQL 和参数
    const fieldsToUpdate = [];
    const values = [];
    if (title !== undefined) fieldsToUpdate.push('title = ?'), values.push(title);
    if (content !== undefined) fieldsToUpdate.push('content = ?'), values.push(content);
    if (imgUrl !== undefined) fieldsToUpdate.push('imgUrl = ?'), values.push(imgUrl);
    if (tags !== undefined) fieldsToUpdate.push('tags = ?'), values.push(tags);
    if (likes !== undefined) fieldsToUpdate.push('likes = ?'), values.push(likes);
    if (liulan !== undefined) fieldsToUpdate.push('liulan = ?'), values.push(liulan);
    // 如果没有提供更新字段
    if (fieldsToUpdate.length === 0) {
        return res.status(400).json({error: 'At least one field (title, content, imgUrl, tags) is required to update'});
    }
    // 添加 ID 到参数数组
    values.push(id);
    // 动态生成 SQL
    const sql = `UPDATE posts SET ${fieldsToUpdate.join(', ')} WHERE id = ?`;
    // 执行更新操作
    db.query(sql, values, (err, result) => {
        if (err) {
            console.error('更新数据失败:', err);
            return res.status(500).json({error: 'Failed to update post'});
        }

        if (result.affectedRows === 0) {
            return res.status(404).json({error: 'Post not found'});
        }

        res.status(200).cc({message: 'Post updated successfully'}, 0);
    });
}

exports.deletePost = (req, res, next) => {
    const sql = "DELETE FROM posts WHERE id = ?";
    db.query(sql, req.params.id, (err, result) => {
        if (err) throw err;
        return res.cc({message: 'Post deleted successfully'}, 0)
    });
}